import Cookies from 'js-cookie'
import router from '../router' // 假设你的 router 文件在同一目录下
import store from '../store' // 假设你的 store 文件在同一目录下
import { getUserByToken } from '@/api/mall/user'

const TokenKey = 'token'

export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export function getUserId(noauth) {
  const token = Cookies.get('token')

  if (!token && !noauth) {
    window.alert('hh1')
    router.push('/login')
  } else {
    return getUserByToken().then(res => {
      const userId = res.data
      if (userId) {
        return userId
      }
      window.alert('hh2')
      router.push('/login')
      return Promise.reject(new Error('no auth'))
    }).catch(error => {
      console.error('Error getting user ID:', error)
      throw error
    })
  }
}
